<?php

namespace app\api\controller;
use addons\epay\library\Service;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use app\admin\controller\store\Technicianserve;
use app\admin\model\technician\Technicianlabel;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Coupon;
use app\common\model\Follow;
use app\common\model\History;
use app\common\model\InformLog;
use app\common\model\InviteLog;
use app\common\model\MoneyLog;
use app\common\model\OrderComment;
use app\common\model\ParentMoneyLog;
use app\common\model\Recharge;
use app\common\model\UseCoupon;
use app\common\model\Withdraw;
use fast\Random;
use http\Exception;
use think\Cache;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\Validate;
use anerg\OAuth2\OAuth;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin','showinvite', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','about','qrcode','wxlogin','qqlogin','notifyx','returnx','getUniMobile'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $userinfo = [
            'id' => $this->auth->id,
            'nickname' => $this->auth->nickname,
            'avatar' => $this->auth->avatar,
            'gender' => $this->auth->gender,
            'money' => $this->auth->money,
//            'position' => $this->auth->postion,
            'mobile' => $this->auth->mobile,
            'serve_follow' => $this->auth->serve_follow,
            'technician_follow' => $this->auth->technician_follow,
            'store_follow' => $this->auth->store_follow
        ];
        //优惠券数量
        $userinfo['coupon_count'] = UseCoupon::where(['uid' =>$this->auth->id, 'status' => 1])->count();
        $this->success('', $userinfo);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     * @param string $postion 用户身份
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $postion=$this->request->post('postion',1);
        if (!$account || !$password) {
            $this->error(__('参数不能为空'));
        }
        $ret = $this->auth->login($account, $password,$postion);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
          //融云token
          $token = getRongyunToken($data['userinfo']['id'], $data['userinfo']['nickname'], $data['userinfo']['avatar']);
          $data['rong_token'] = $token;
            $this->success(__('登录成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     * postion  身份 1 用户 2 技师 3 店铺
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $postion=$this->request->request('postion');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
//        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
//            $this->error(__('Captcha is incorrect'));
//        }
        $avatar=Config('site.default_avatar');
        $user = \app\common\model\User::where(['mobile'=>$mobile,'postion'=>$postion])->find();
        $extend = [
            'postion'=>$postion,
            'avatar'=>$avatar
        ];
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            if ($user->del_flag != 0) {
                $this->error(__('账号已注销'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), $mobile, $extend);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $token = getRongyunToken($data['userinfo']['id'], $data['userinfo']['nickname'], $data['userinfo']['avatar']);
            $data['rong_token'] = $token;
            $this->success(__('登录成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $password = $this->request->post('password');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $postion=$this->request->request('postion',1);//注册身份 1 用户 2 技师 3 店铺 默认注册1
        $invitecode = $this->request->request('invitecode');
//      $long       = $this->request->request('long');
//      $lat        = $this->request->request('lat');
        adlog('注册邀请码', $invitecode);
//        if (isset($invitecode)) {
//            $userinfo = \app\common\model\User::where('invite_code', $invitecode)->find();
//            if (!$userinfo) {
//                $this->error('邀请人信息错误,请重试');
//            }
//        }
        $invite_code = rand(1111, 9999);
        if (\app\common\model\User::where('invite_code', $invite_code)) {
            $invite_code = rand(1111, 9999);
        }
        $avatar=config('site.default_avatar');
        $invite =$this->qrcode($invite_code);

      $inviter=[];
      if($invite_code){
        $inviter=\app\common\model\User::where(['invite_code'=>$invite_code])->find()?:[];
      }
     $extend=[
         'invite_code' =>$invite_code,
         'invite_url' =>$invite,
       'avatar'   => $avatar,
       'postion'=>$postion,
       'inviter_id'      => $inviter?$inviter['id']:0
     ];
     if (!$mobile || !$password) {
         $this->error(__('参数不能为空'));
     }
     if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
         $this->error(__('手机号格式错误'));
     }
     $ret = Sms::check($mobile, $code, 'register');

        if (!$ret) {
            $this->error(__('验证码错误'));
        }
     $ret = $this->auth->register($mobile,$password,$mobile,$extend);
     if ($ret) {
         $data = ['userinfo' => $this->auth->getUserinfo()];
         $Invitee = $this->invitecode($invitecode);
         if($Invitee){
             $data = [
                 'Invitee'    => $Invitee['Invitee'],
                 'Invitees'   => $this->auth->id,
                 'createtime' => time()
             ];
             Invitelog::create($data);
         }
       $token = getRongyunToken($data['userinfo']['id'], $data['userinfo']['nickname'], $data['userinfo']['avatar']);
       $data['rong_token'] = $token;
         $this->success(__('注册成功'), $data);
     } else {
         $this->error($this->auth->getError());
     }
 }

 /**
  * 退出登录
  * @ApiMethod (POST)
  */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('无效的参数'));
        }
        $this->auth->logout();
        $this->success(__('退出成功'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $gender = $this->request->post('gender');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $user->username = $username;
        }
        if ($nickname) {
            $user->nickname = $nickname;
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }
        if ($gender) {
            $user->gender = $gender;
        }
        $user->save();
        $this->success('修改成功');
    }

//    /**
//     * 修改邮箱
//     *
//     * @ApiMethod (POST)
//     * @param string $email 邮箱
//     * @param string $captcha 验证码
//     */
//    public function changeemail()
//    {
//        $user = $this->auth->getUser();
//        $email = $this->request->post('email');
//        $captcha = $this->request->post('captcha');
//        if (!$email || !$captcha) {
//            $this->error(__('Invalid parameters'));
//        }
//        if (!Validate::is($email, "email")) {
//            $this->error(__('Email is incorrect'));
//        }
//        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
//            $this->error(__('Email already exists'));
//        }
//        $result = Ems::check($email, $captcha, 'changeemail');
//        if (!$result) {
//            $this->error(__('Captcha is incorrect'));
//        }
//        $verification = $user->verification;
//        $verification->email = 1;
//        $user->verification = $verification;
//        $user->email = $email;
//        $user->save();
//
//        Ems::flush($email, 'changeemail');
//        $this->success();
//    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {

        $mobile = $this->request->post('mobile');
        $user    = $this->auth->getUser();
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user['id'])->where('postion',$user['postion'])->find()) {
            $this->error(__('手机号已存在'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('验证码错误'));
        }
        $verification = $user['verification'];
        $verification->mobile = 1;
        $user->verification = $verification;
        $user['mobile'] = $mobile;
        $user->save();
        Sms::flush($mobile, 'changemobile');
        $this->success('修改成功');
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
//        $userinfo = $this->auth->getUser();
        $mobile = $this->request->post("mobile");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        $postion=$this->request->request('postion');
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('密码长度6-30位'));
        }
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('手机号格式不正确'));
            }
            $user = \app\common\model\User::where(['mobile'=>$mobile,'postion'=>$postion])->find();
            if (!$user) {
                $this->error(__('用户不存在'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('无效的验证码'));
            }
            Sms::flush($mobile, 'resetpwd');
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('重置密码成功'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 绑定微信/支付宝
     *
     * @param string   type        绑定类型'alipay', 'wechat',
     * @param string   name        绑定姓名
     * @param string   account       绑定账号
     */
    public function binding()
    {
        $user = $this->auth->getUser();
        $type = $this->request->request('type');
        $name = $this->request->request('name');
        $account = $this->request->request('account');
        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("绑定类型错误");
        }
        if (!$name || !$account) {
            $this->error('绑定数据不能为空');
        }
        if (trim($name) == 'null' || trim($account) == 'null') {
            $this->error('参数不能为字符串"null"');
        }
        if (trim($name) == 'undefined' || trim($account) == 'undefined') {
            $this->error('参数不能为字符串"undefined"');
        }
        switch ($type) {
            case 'alipay':
                $user->ali_account = $account;
                $user->ali_name = $name;
                break;
            case 'wechat':
                $user->wx_account = $account;
                $user->wx_name = $name;
                break;
            default:
                break;
        }
        $result = $user->save();
        if ($result) {
            $this->success('绑定成功');
        } else {
            $this->error('绑定失败');
        }
    }

    /**
     * 设置密码
     */

    public function Setpassword()
    {
        $userinfo = $this->auth->getUser();
        $password = $this->request->request('password');
        $newpassword = $this->request->post("newpassword");
//        if ($userinfo->password =$password) {
//            $this->error('新密码不能与旧密码相同');
//        }
        if (!$password) {
            $this->error('参数不能为空');
        }
        if ($password != $newpassword) {
            $this->error('两次密码不一致');
        }
        //模拟一次登录
        $this->auth->direct($userinfo->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('设置密码成功'));
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 关于我们
     */

    public function about()
    {
        $logo = config('site.logo');           //logo图片
        $customer_phone = config('site.serve_phone'); //客服电话
//        $register_terms=config('site.register_terms');//注册协议
//        $privacy_agreement=config('site.privacy_agreement');//隐私协议
        $app_version = config('site.app_version');
        $hezuo_phone = config('site.cooperation_phone');
        $data = [
            'logo' => $logo,
            'server' => $customer_phone,
            'app_version' => $app_version,
            'hezuo_phone' => $hezuo_phone
        ];
        $this->success('查询成功', $data);
    }

    /**
     * 我的评价
     */

    public function mycomment()
    {

        $uid = $this->auth->id;
        $comment = OrderComment::where('uid', $uid)->field('id,uid,createtime,star,content,image,serve_id,technician_id,address')->select();
        $user = \app\common\model\User::where('id', $uid)->field('id,avatar,nickname')->find();

           if(!empty($comment)) {
               foreach ($comment as $key => $value) {
                   $technician = \app\common\model\Technician::where('technician_id', '=', $value['technician_id'])->field('technician_id,store_id,technician_avatar,real_name')->find();
                   $serve = \app\common\model\Serve::where('id', '=', $value['serve_id'])->field('serve_name,id')->find();
                   $store = \app\common\model\Store::where('store_id', '=', $technician->store_id)->field('name,store_id')->find();
                   $value['createtime'] = date('Y-m-d H:i', $value['createtime']);
                   $value['user'] = $user;
                   $value['technician'] = $technician;
                   $value['serve'] = $serve;
                   $value['store'] = $store;
               }
           }
        $this->success('查询成功', $comment);
    }


    /**
     * 我的浏览历史
     */

    public function myHistory()
    {
        $uid = $this->auth->id;
        $page=$this->request->request('page',1);
        $history = History::where('uid', '=', $uid)->page($page,10)->select();
        if ($history) {
            foreach ($history as $key => $value) {
                $serve = \app\common\model\Serve::where('id', '=', $value['serve_id'])->field('id,serve_name,serve_image,serve_price,serve_details,store_id,sales,feedback,time_label,serve_duration')->find();
                $tserve=\app\common\model\TechnicianServe::where(['store_id'=>$serve['store_id']])->find();
                $store = \app\common\model\Store::where('store_id', '=',$tserve['store_id'])->field('store_id,name')->find();
                $history[$key]['serve'] = $serve??[];
              $history[$key]['store'] = $store??[];
            }
        }
        $this->success('查询成功', $history ?? []);
    }


    /**
     * 清空浏览历史
     */
    public function clearHistory()
    {
        $uid = $this->auth->id;
        $res = History::where('uid', '=', $uid)->delete();
        if ($res) {
            $this->success('清空成功');
        } else {
            $this->error('清空失败');
        }
    }

    /**
     * 我的举报投诉列表
     */
    public function Informlist()
    {
        $uid = $this->auth->id;
        $type = $this->request->request('type');//1 待处理 2 已处理
$page=$this->request->request('page',1);
$where=[];
if($type){
    $where['is_sendto']=$type;
}
$where['uid']=$uid;
        $inform = InformLog::where($where)->field('id,uid,inform_title,content,images,inform_time,content,is_sendto')->page($page,10)->select();
        if ($inform) {
            foreach ($inform as $key => $value) {
                $inform_time = date('Y-m-d', $value['inform_time']);
                if($value['is_sendto']==1){
                    $value['is_sendto']='待处理';
                }else if($value['is_sendto']==2){
                    $value['is_sendto']='已处理';
                }
                $order = \app\common\model\Order::where(['id' => $value['id']])->field('id,order_status,store_id,serve_id,appointment_time')->find();
                $store = \app\common\model\Store::where('store_id', '=', $order['store_id'])->field('store_id,name')->find();
                $serve = \app\common\model\Serve::where('id', '=', $order['serve_id'])->field('id,serve_name,serve_image,serve_price')->find();
                $inform[$key]['store'] = $store;
                $inform[$key]['serve'] = $serve;
                $inform[$key]['order'] = $order;
                $inform[$key]['inform_time'] =$inform_time;
            }
        }
        $this->success('查询成功', $inform ?? []);
    }


    /**
     * 撤销投诉
     */

    public function revokeinform()
    {

        $uid = $this->auth->id;
        $inform_id = $this->request->request('inform_id');
        $inform = InformLog::where(['id' => $inform_id, 'is_sendto' => 1, 'uid' => $uid])->find();
        if (!$inform) {
            $this->error('当前举报不存在');
        }
        $res = $inform->delete();
        if ($res) {
            $this->success('撤销成功');
        } else {
            $this->error('撤销失败');
        }
    }


    /**
     * 我的关注
     */

    public function myfollow()
    {

        $uid = $this->auth->id;
        $lon=$this->request->request('lon');
        $lat=$this->request->request('lat');
        $type = $this->request->request('type');//1 技师 2 服务 3 店铺
        $follow = Follow::where(['uid' => $uid, 'follow_status' => 1,'type'=>$type])->field('id,technician_id,uid,serve_id,store_id')->select();
        if ($type == 1) {

            if ($follow) {
                foreach ($follow as $key => $value) {
                    $time=time();
                    $times=date('w',$time);
                    $te=\app\admin\model\Technician::where(['work_day'=>['like',"%$times%"]])->find();
                    $technician = \app\common\model\Technician::where('technician_id', '=', $value['technician_id'])->field('technician_id,technician_address,technician_age,technician_name,technician_avatar,store_id,lon,lat,introduction,technician_label')->find();
                    if($technician) {
                        $technician['distance'] = distance($lon, $lat, $technician['lon'], $technician['lat']);//距离我km
                        $technician['technician_address'] = mb_substr($technician['technician_address'], 0, 2);;//技师常驻地址
                        if ($technician['technician_label']) {
                            $label = Technicianlabel::where(['id' => $technician['technician_label']])->find();
                            $technician['technician_label'] = $label->technician_label;
                        }
                        if ($te) {
                            $isset_order = \app\common\model\Order::where(['order_status' => ['in', [2, 3, 4, 5]], 'technician_id' => $te['technician_id']])->find();
                            if ($isset_order) {
                                $technician['earliestappionent_time'] = date('H:i', $isset_order['endserve_time']);
                            } else {
                                $technician['earliestappionent_time'] = date('H:i', time());
                            }
                        } else {
                            $technician['earliestappionent_time'] = '';
                        }
                        $store = \app\common\model\Store::where('store_id', '=', $technician['store_id'])->field('store_id,name')->find();
                        $follow[$key]['store'] = $store ?: [];
                        $follow[$key]['technician'] = $technician;
                    }
                }
            }
        } else if ($type == 2) {
            if ($follow) {
                foreach ($follow as $key => $value) {
                    $serve = \app\common\model\Serve::where(['id'=>$value['serve_id'],'serve_status'=>1,'is_added'=>0])->field('id,serve_name,serve_image,store_id,serve_price')->find();
                    $tserve=\app\admin\model\store\Technicianserve::where(['serve_id'=>['in',$serve['id'],'store_id'=>$serve['store_id']]])->find();
                    if($tserve){
                        $store = \app\common\model\Store::where('store_id', '=', $serve['store_id'])->field('name,store_id')->find();
                    }
                    $follow[$key]['store'] = $store??[];
                    $follow[$key]['serve'] = $serve??[];
                }
            }
        } else if($type==3){
            if ($follow) {
                foreach ($follow as $key => $value) {
                    $store = \app\common\model\Store::where('store_id', '=', $value['store_id'])->field('name,image,feedback')->find();
                    $follow[$key]['store'] = $store;
                }
            }
        }
        $this->success('查询成功', $follow ?? []);
    }


    /**
     * 提现
     * 提现类型 type alipay 支付宝 wechat 微信
     */

    public function withdraw()
    {
        $uid = $this->auth->id;
        $money = $this->request->request('money');
      $postion = $this->request->request('postion');//1 用户 2 技师 3 商家
        $name = $this->request->request('name');
        $type = $this->request->request('type'); //alipay 支付宝 wechat 微信


        if (!$money || $money < 0) {
            $this->error("提现金额必须大于0");
        }
        $user = \app\common\model\User::where(['id'=>$uid,'postion'=>$postion])->find();
        if($user){
          if ($user->money < $money) {
            $this->error('余额不足,暂不能提现');
          }
        }
        if (!in_array($type, ['alipay', 'wechat'])) {
            $this->error('提现方式错误');
        }
//    if(!$user->wx_count||$user->ali_count){
//      $this->error('提现账号');
//    }

        if ($type =="alipay"){
            if (!$user->ali_account) {
                $this->error('提现账号不能为空');
            }
        } else if($type == "wechat") {
            if (!$user->wx_account) {
                $this->error('提现账号不能为空');
            }
        }
      $commission = config('site.service_charge');//抽成
      if ($commission > 0) {
        $handingfee = bcmul($money,($commission / 100),2);  // 手续费
        $amount     = bcsub($money,$handingfee,2);          // 可提现金额
      } else {
        $handingfee = 0;
        $amount      = 0;
      }
        $orderid = makePaySn($uid);
      if($type=='wechat'){
        $types="微信";
      }else{
        $types="支付宝";
      }
        $memo = $types.'提现';
        $data = [
            'user_id' => $uid,
            'position' => $postion,
            'amount' => $amount,
            'money' => $user->money,
            'wx_account' => $user->wx_account??'',
            'ali_count' => $user->ali_account??'',
            'type' => $types,
            'status' => 'created',
            'memo' => $memo,
             'handingfee'=>$handingfee,
            'name' => $name,
            'createtime' => time(),
            'orderid' => $orderid
        ];
        $res = Withdraw::create($data);
        \app\common\model\User::money($amount, $uid, $memo,2,$postion,1);
        if ($res) {
            $this->success('提交成功,待审核');
        } else {
            $this->error('提交失败');
        }
    }

  /**
   * 提现记录
   */

  public function withdrawlist(){
    $uid=$this->auth->id;
    $postion=$this->auth->postion;
    $page=$this->request->request('page',1);
    $withdraw=Withdraw::where(['user_id'=>$uid,'position'=>$postion])->field('position,memo,amount,createtime')->page($page,10)->order('createtime','desc')->select();
    foreach ($withdraw as $item){
      $item['createtime']=date('Y-m-d H:i:s',$item['createtime']);
    }
    $this->success('',$withdraw);
  }

    /**
     * 邀请封装
     *
     */
    public function invitecode($invitecode)
    {
        if ($invitecode) {
            $userinfo = \app\common\model\User::where('invite_code', $invitecode)->find();
            if ($userinfo) {
                return ['Invitee' => $userinfo['id']];
            } else {
                return false;
            }
        }
    }


    /**
     * 修改用户二维码地址
     *
     */
    public function upt_qrcode()
    {
        $userlist = \app\admin\model\User::where('id', '>', 0)->select();
        foreach ($userlist as $v) {
            $path = $this->qrcode($v['invite_code']);
            $v->save(['invite_url' => $path]);
        }
    }

    /**
     * 根据用户code生成二维码
     *
     */
    public function qrcode($text)
    {
        $config = get_addon_config('qrcode');
        $params = [];
//        $params['text'] = $text;
        $params['text'] = request()->domain() . '/index/index/invite/?channelCode=10001&code=' . $text;
        $qrCode = \addons\qrcode\library\Service::qrcode($params);
        $returnPath = '';
        // 写入到文件
        if ($config['writefile']) {
            $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/' . date('Ymd') . '/';
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            if (is_really_writable($qrcodePath)) {
                $filePath = $qrcodePath . md5(implode('', $params)) . '.' . $config['format'];
                $qrCode->writeFile($filePath);
                $key = md5(implode('', $params)) . '.' . $config['format'];
                return '/uploads/qrcode/' . date('Ymd') . '/' . $key;
            }
        }
        return ['path' => $returnPath];
    }

    /**
     * 用户余额明细
     *
     */
    public function usermoneylog()
    {
        $uid = $this->auth->id;
      $page=$this->request->request('page',1);
        $list = MoneyLog::where(['user_id'=>$uid,'is_clearing'=>1])->page($page,10)->order('createtime', 'desc')->select();
        foreach ($list as $v) {
            $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
        }
        $this->success('', $list);
    }



    /**
     * 邀请列表
     *
     */
    public function invite_info()
    {
        $uid = $this->auth->id;
        $userinfo = \app\common\model\User::where('id', $uid)->field('id,username,nickname,mobile,avatar,gender,postion,invite_code,invite_url')->find();
        $userinfo['invite_list'] = \app\admin\model\User::where('inviter_id', $uid)->field('id,nickname,avatar')->select();
//        $userinfo['invite_income']=ParentMoneyLog::where('pid','=',$uid)->field('pid,pprice,note')->select();
        $this->success('', $userinfo);
    }




    /**
     * 微信登录
     *
     * @param string $openid 微信openid
     */
    public function wxlogin()
    {

        $openid     = $this->request->request('openid');
        $nickname = $this->request->request('nickName', '');
        $avatar = $this->request->request('avatar', '');
        $gender = $this->request->request('gender', 0);
        $postion=$this->request->request('postion',1);
        $invitecode = $this->request->request('invitecode','');
        adlog('邀请码', $invitecode);
        if (!$openid) {
            $this->error('没有登陆信息');
        }
        $user = \app\common\model\User::where('openid', $openid)->find();
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('账号异常!'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $user_code = rand(1111, 9999);
            if(\app\common\model\User::where('invite_code', $user_code)){
                $user_code = rand(1111, 9999);
            }
            $path = $this->qrcode($user_code);
            $inviter=[];
            if( $invitecode){
                $inviter=\app\common\model\User::where(['invite_code'=> $invitecode])->find()?:[];
            }
            $code_path = $path;
            $avatar = $avatar ?: Config::get('site.default_avatar');
            $extend = [
                'nickname' => $nickname,
                'gender' => $gender,
                'avatar' => $avatar,
                'openid' => $openid,
                'invite_code' => $user_code,
                'invite_url'  => $code_path,
                'postion'=>$postion,
                'inviter_id'      => $inviter?$inviter['id']:0
            ];
            $ret = $this->auth->wxRegister($openid, $extend);
        }
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $Invitee = $this->invitecode($invitecode);
            if($Invitee){
                $data = [
                    'Invitee'    => $Invitee['Invitee'],
                    'Invitees'   => $this->auth->id,
                    'createtime' => time()
                ];
                Invitelog::create($data);
            }
            $token = getRongyunToken($data['userinfo']['id'], $data['userinfo']['nickname'], $data['userinfo']['avatar']);
            $data['rong_token'] = $token;
            $this->success(__('登陆成功!'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * qq登录
     *
     * @param string $openid qqopenid
     */
    public function qqlogin()
    {
        $openid     = $this->request->request('openid');
        $nickname = $this->request->request('nickname', '');
        $avatar = $this->request->request('figureurl_qq_2', '');
        $gender = $this->request->request('gender', 0);
        $postion=$this->request->request('postion',1);
        $invitecode = $this->request->request('invitecode','');
        adlog('邀请码', $invitecode);
        if (!$openid) {
            $this->error('没有登陆信息');
        }
        $user = \app\common\model\User::where('qq_openid', $openid)->find();
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('账号异常!'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $user_code = rand(1111, 9999);
            if(\app\common\model\User::where('invite_code', $user_code)){
                $user_code = rand(1111, 9999);
            }
            $path = $this->qrcode($user_code);
//            if(!$path){
//                $path = $this->qrcode($user_code);
//            }
            $code_path = $path;
            $avatar = $avatar ?: Config::get('site.default_avatar');
            $extend = [
                'nickname' => $nickname,
                'gender' => $gender,
                'avatar' => $avatar,
                'qq_openid' => $openid,
                'invite_code' => $user_code,
                'invite_url'  => $code_path,
                'postion'=>$postion
            ];
            $ret = $this->auth->qqRegister($openid, $extend);
        }
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('登陆成功!'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 充值
     */

    public function recharge()
    {
        $uid = $this->auth->id;
        $money = $this->request->request('money');
        $pay_type = $this->request->request('pay_type');
        if (!$money) {
            $this->error('请选择充值金额');
        }
        if (!$pay_type || !in_array($pay_type, ['wechat', 'alipay'])) {
            $this->error('支付方式错误');
        }
        $out_trade_no = 'R' . $uid . date('YmdHis') . rand(1000, 9999);
        $data = [
            'order_sn' => $out_trade_no,
            'status' => 0,
            'uid' => $uid,
            'payment_type' => $pay_type,
            'money' => $money,
            'createtime' => time(),
            'meno' => $this->auth->username . '用户充值' . $money . '元到钱包'
        ];
        $res = Recharge::create($data);
        if (!$res) {
            $this->error('创建充值订单出错');
        }
        $title = '用户充值';
        $notifyurl = $this->request->root(true) . '/api/user/notifyx/paytype/' . $pay_type . '/out_trade_no/' . $out_trade_no;
        $returnurl = $this->request->root(true) . '/api/user/returnx/paytype/' . $pay_type . '/out_trade_no/' . $out_trade_no;
        $response = \addons\epay\library\Service::submitOrder($money, $out_trade_no, $pay_type, $title, $notifyurl, $returnurl, 'app');
        adlog('充值支付参数', $response);
        if ($pay_type == 'wechat') {
            $response = json_decode($response);
        }
        $this->success('', ['response' => $response]);
    }

    /**
     * 支付成功回调
     */

    public function notifyx()
    {
        $paytype = $this->request->param('paytype');
        adlog('支付方式', $paytype);
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        adlog('用户充值订单回调', $data);
        Db::startTrans();
        try {
            $out_trade_no = $data['out_trade_no'];
                $order = Recharge::get(['order_sn' => $out_trade_no]);
                if( $order) {
                    $order->status = 1;
                    $order->pay_time = time();
                    $order->save();
                    \app\common\model\User::money($order->money, $order->uid, '充值', 1, 1, 1);
                }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        echo 'success';
    }

    /**
     * 支付返回，仅供开发测试
     */
    public function returnx()
    {
        $paytype      = $this->request->param('paytype');
        $out_trade_no = $this->request->param('out_trade_no');
        $pay          = Service::checkReturn($paytype);
        if (!$pay) {
            $this->error('签名错误','');
        }

        //你可以在这里通过out_trade_no去验证订单状态
        //但是不可以在此编写订单逻辑！！！

        $this->success("请返回网站查看支付结果",addon_url("epay/index/index"));
    }


    /**
     * 手机号一键登录
     * @param $accessKeyId
     * @param $accessKeySecret
     *
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new \Darabonba\OpenApi\Models\Config([
            // 您的 AccessKey ID
            "accessKeyId" =>$accessKeyId,
            // 您的 AccessKey Secret
            "accessKeySecret" =>$accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dypnsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }


    public static function main()
    {
        $client = self::createClient("LTAI5tLw3jsRJpTiZQ2NgYNW", "wimjtXagmWILw37HcLDUN1aTdoPMWW");
        $sendSmsRequest = new SendSmsRequest([]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $client->sendSmsWithOptions($sendSmsRequest, $runtime);
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 如有需要，请打印 error
            Utils::assertAsString($error->message);
        }
    }

    /**
     * uniapp一键登录获取手机号
     *
     * @ApiMethod (POST)
     * @param string $accessToken App端SDK获取的登录Token
     * @param string $openid App端SDK获取的登录openid
     */
    public function getUniMobile()
    {
        $invitecode     = $this->request->request('invitecode');
        $accessToken    = $this->request->post('accessToken');
        $openid         = $this->request->post('openid');
        $mobile         = $this->request->request('mobile');
        $postion=$this->request->request('postion');
        adlog('参数',['mobile'=>$mobile,'一键登录邀请码'=>$invitecode]);
        if(!$mobile ){
            $this->error('参数不能为空');
        }
        $user = \app\common\model\User::where(['mobile'=>$mobile,'postion'=>$postion])->find();
        if($user){
            $this->auth->direct($user['id']);
            $data    = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('登录成功'), $data);
        }else{
            //默认头像
            $user_code = rand(1111, 9999);
            if(\app\common\model\User::where('invite_code', $user_code)){
                $user_code = rand(1111, 9999);
            }
            $path = $this->qrcode($user_code);
//            if(!$path){
//                $path = $this->qrcode($user_code);
//            }
            $code_path = $path;
            $avatar    = config('site.default_avatar');
            $extend    = [
                'nickname'    => preg_match("/^1[3-9]{1}\d{9}$/", $mobile) ? substr_replace($mobile, '****', 3, 4) : $mobile,
                'gender'      => 0,
                'avatar'      => $avatar,
                'invite_code' => $user_code,
                'invite_url'  => $code_path,
                'postion'=>$postion
            ];
            $ret       = $this->auth->register($mobile, '123456',$mobile, $extend);
            if($ret){
                $data    = ['userinfo' => $this->auth->getUserinfo()];
                $Invitee = $this->invitecode($invitecode);
                if($Invitee){
                    $data = [
                        'Invitee'    => $Invitee['Invitee'],
                        'Invitees'   => $this->auth->id,
                        'createtime' => time()
                    ];
                    Invitelog::create($data);
                }
                $token = getRongyunToken($data['userinfo']['id'], $data['userinfo']['nickname'], $data['userinfo']['avatar']);
                $data['rong_token'] = $token;
                $this->success(__('登录成功'), $data);
            }else{
                $this->error($this->auth->getError());
            }
        }
    }

    /**
     * 优惠券列表
     */

    public function CouponList(){
        $where=[];
        $where['status']=0;
        $coupon=Coupon::where($where)->select();
        foreach ($coupon as $key=>$value){
            $value['end_time']=date('Y-m-d',  $value['end_time']);
        }
        $this->success('',$coupon);
    }


//    /**
//     * 兑换优惠券
//     */
//
//    public function convertCoupon(){
//        $code=$this->request->request('code');
//        $uid=$this->auth->id;
//        if(!$code){
//          $this->error('请输入兑换码');
//        }
//        $coupons=Coupon::where(['status'=>0,'code'=>$code])->find();
//        if(!$coupons){
//            $this->error('该兑换码已兑换过');
//        }
//        $data=[
//            'uid'=>$uid,
//            'get_time'=>time(),
//            'coupon_id'=>$coupons->id,
//            'expiration_time'=>$coupons->end_time,
//            'status'=>1,
//            'createtime'=>time(),
//        ];
//        $res=UseCoupon::create($data);
//        Coupon::where('id','=',$coupons->id)->update(['status'=>1]);
//        if($res){
//            $this->success('兑换成功');
//        }else{
//            $this->error('兑换失败');
//        }
//    }

    /**
     * 领取优惠券
     */

    public function useCoupon(){
        $coupon_id=$this->request->request('coupon_id');
        $uid=$this->auth->id;
        $postion=$this->auth->postion;
        if($postion!=1){
            $this->error('当前身份不是用户');
        }
        $coupons=Coupon::where('id','=',$coupon_id)->find();
        if($coupons){
           Coupon::where('id','=',$coupon_id)->update(['status'=>1]);
        }
        $data=[
            'uid'=>$uid,
            'get_time'=>time(),
             'coupon_id'=>$coupon_id,
            'expiration_time'=>$coupons->end_time,
            'status'=>1,
            'createtime'=>time(),
        ];
        $res=UseCoupon::create($data);
        if($res){
            $this->success('领取成功');
        }else{
            $this->error('领取失败');
        }
    }


    /**
     * 我的优惠券
     */

    public function userCoupon(){
        $uid=$this->auth->id;
        $money=$this->request->request('money');
//        $usercoupon=UseCoupon::where(['uid'=>$uid,'status'=>1])->select();
              $usercoupon=UseCoupon::alias('us')
            ->join('coupon c','c.id=us.coupon_id')
                  ->where('c.term','>=',$money)
            ->where('us.uid','=',$uid)
            ->where('us.status','=','1')

            ->select();

              foreach ($usercoupon as $key=>$value){
//                  var_dump(111);
//                  var_dump($value);
                  $value['end_time']=date('Y-m-d',$value['end_time']);
              }
        $this->success('',$usercoupon);
    }

    /**
     * 删除评价
     */

    public function del_comment(){
        $uid=$this->auth->id;
        $comment_id=$this->request->request('comment_id');
        if(!$comment_id){
            $this->error('参数不能为空');
        }
        $comment=OrderComment::where(['id'=>$comment_id,'uid'=>$uid])->find();
        if(!$comment){
            $this->error('评论数据不存在');
        }
        $res=$comment->delete();
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }


    /**
     * 微信 绑定手机号
     */
    public function bindMobile(){
        $mobile=$this->request->request('mobile');
        $openid = $this->request->request('openid');
        $postion=$this->request->request('postion');//身份 1 用户 2 技师 3 店铺
        $code     = $this->request->request('code');//验证码
        $ret = Sms::check($mobile,$code,'bind');
        if (!$ret) {
            $this->error(__('验证码错误!'));
        }
        if (!$openid) {
            $this->error('缺少openid');
        }
           $user=\app\common\model\User::where(['openid'=>$openid,'postion'=>$postion])->find();
            if(!empty($user->mobile)){
              $this->error('当前手机号已被绑定');
            }
           if($user){
               $user->mobile=$mobile;
               $user->save();
           }
           $technician=\app\admin\model\Technician::where(['uid'=>$user->id])->find();
           if($technician){
             $technician->technician_phone=$mobile;
             $technician->save();
           }
       $this->success('绑定手机号成功');
    }


    /**
     * 查询可提现金额
     */

    public function withdrawmoney(){
      $money=$this->auth->money;
      $this->success('查询成功',['price'=>$money]);
    }

    /**
     * 查询提现账号
     */

    public function showwithdraw()
    {
      $user = $this->auth->getUser();
      $data = [
        'wechat' => ['wx_account' => $user->wx_account?:'','wx_name' => $user->wx_name?:''],
        'alipay' => ['ali_account' => $user->ali_account?:'','ali_name' => $user->ali_name?:''],
      ];
      $this->success('请求成功',$data);
    }

    /**
     * 查询邀请福利
     */

    public function showinvite(){


        $data=[
          'fuli1'=>config('site.fuli1'),
        'fuli2'=>config('site.fuli2')
        ];
        $this->success('查询成功',$data);
    }

}
